import loadable from '@loadable/component';

let uid = 1;

function createUid() {
  return `_${uid++}`;
}

function dynamicImport(Comp) {
  return loadable(Comp);
}

// 格式化路由数据
export function format(routes) {
  const routeMap = {};
  function toMap(data, parent) {
    data.forEach((item) => {
      item.id = createUid();
      if (item.component) {
        item.component = dynamicImport(item.component);
      }
      if (parent && !parent.layout) {
        item.parentPaths = [...(parent.parentPaths || []), parent.path];
        item.parentIds = [...(parent.parentIds || []), parent.id];
      }
      if (!item.redirect && item.path) {
        routeMap[item.path] = item;
      }
      if (item.routes?.length) {
        toMap(item.routes, item);
      }
    });
  }
  toMap(routes);
  function toArr(data) {
    return data.reduce((prev, { routes: children, ...rest }) => {
      if (!children?.length) {
        return prev.concat(rest);
      }
      if (rest.layout) {
        return prev.concat({ ...rest, routes: toArr(children) });
      }
      if (rest.component) {
        return prev.concat(rest, ...toArr(children));
      }
      return prev.concat(...toArr(children));
    }, []);
  }
  const routeArr = toArr(routes);
  return { routeArr, routeMap };
}
